package com.zlyx.easy.mybatis.interceptors;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import com.zlyx.easy.core.utils.LogUtils;
import com.zlyx.easy.database.interceptors.AbstractResultSetInterceptor;
import com.zlyx.easy.database.local.ReturnType;

/**
 * @Auth 赵光
 * @Describle
 * @2019年1月14日 下午12:28:08
 */
@Component
@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class }) })
public class ResultSetInterceptor extends AbstractResultSetInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		ResultSetHandler resultSetHandler = (ResultSetHandler) invocation.getTarget();
		Field resultField = resultSetHandler.getClass().getDeclaredField("mappedStatement");
		resultField.setAccessible(true);
		MappedStatement mappedStatement = (MappedStatement) resultField.get(resultSetHandler);
		List<ResultMap> resultMaps = mappedStatement.getResultMaps();
		int count = resultMaps.size();
		Class<?> resultType = resultMaps.get(0).getType();
		boolean flag = false;
		if (ReturnType.getType() != null) {
			resultType = ReturnType.getType();
			flag = true;
		}
		if (count > 0 && ReturnType.getType() != null) {
			Statement statement = (Statement) invocation.getArgs()[0];
			try (ResultSet resultSet = statement.getResultSet()) {
				if (flag) {
					return getResults(resultType, resultSet);
				}
			} catch (Exception e) {
				LogUtils.err(e);
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		if (target instanceof ResultSetHandler) {
			return Plugin.wrap(target, this);
		} else {
			return target;
		}
	}

	@Override
	public void setProperties(Properties properties) {
		String dialect = properties.getProperty("dialect");
		LogUtils.info("mybatis intercept dialect:{}", dialect);
	}

}